package com.ship.contract.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ship.common.core.enums.MessageTypeEnum;
import com.ship.common.core.enums.ModuleUrlEnum;
import com.ship.common.core.exception.BusException;
import com.ship.common.core.web.domain.BaseResultCode;
import com.ship.contract.bean.ConExcellentCases;
import com.ship.contract.bean.ConFiles;
import com.ship.contract.bean.ConResourceMain;
import com.ship.contract.bean.ConResourceMemorandum;
import com.ship.contract.mapper.ConResourceMainMapper;
import com.ship.contract.mapper.ConResourceMemorandumMapper;
import com.ship.contract.service.*;
import com.ship.contract.utils.FileUtil;
import com.ship.contract.utils.ObjectUtils;
import com.ship.contract.utils.PingYinUtil;
import com.ship.contract.mapper.ConstantMapper;
import com.ship.system.api.BpmInstanceService;
import com.ship.system.api.RemoteMessageSendService;
import com.ship.system.api.domain.SysMessageSend;
import com.ship.system.api.model.ProcessInstanceParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author tangshixuan
 * @date 2023-8-31
 */
@Service("conResourceMainService")
public class ConResourceMainServiceImpl extends ContractBaseServiceImpl<ConResourceMainMapper, ConResourceMain> implements ConResourceMainService {
    @Autowired
    private ConResourceMainMapper conResourceMainMapper;

    @Autowired
    private ConExcellentCasesService conExcellentCasesService;

    @Autowired
    private ConOperateService conOperateService;

    @Autowired
    private ConAllLabelService conAllLabelService;

    @Autowired
    private ConFilesService conFilesService;

    @Autowired
    private ConResourceMemorandumMapper conResourceMemorandumMapper;

    @Autowired
    private ConstantMapper constantMapper;

    @Resource
    private RemoteMessageSendService remoteMessageSendService;

    @Value("${file.http-domain}")
    private String httpUrl;
    @Value("${file.https-domain}")
    private String httpsUrl;

    @Override
    public void delApply(Long id) {
        ConResourceMain conResourceMain = super.getById(id);
        if(conResourceMain == null){
            throw new BusException("删除申请失败!,该合同不存在", BaseResultCode.GENERAL_ERROR);
        }
        if (conResourceMain.getDelApply() == 1) {
            throw new BusException("当前合同已发起删除申请，请勿重复提交", BaseResultCode.GENERAL_ERROR);
        }
        conResourceMain.setDelApply(1);
        //启动删除审批流程
        ProcessInstanceParam param = new ProcessInstanceParam();
        param.setBussinessId(id);
        param.setBpmKey(BpmInstanceService.SYSTEM_DELETE_BPM_KEY);
        Map<String, Object> map = new HashMap<>();
        map.put("serviceType", 1);
        map.put("module", "con");
        map.put("moduleName", "资源主合同");
        map.put("reason", "");
        param.setParams(map);
        String processInstanceId = bpmInstanceService.startProcessInstance(param);
        conResourceMain.setDeleteProcessInstanceId(processInstanceId);
        super.updateById(conResourceMain);
    }

    @Resource
    BpmInstanceService bpmInstanceService;
    @Override
    public void excellent(ConExcellentCases conExcellentCases, String currentUserName) {
        ConResourceMain conResourceMain = super.getById(conExcellentCases.getId());
        if(conResourceMain == null){
            throw new BusException("删除申请失败!,该合同不存在",BaseResultCode.GENERAL_ERROR);
        }
        ConExcellentCases existByConId = conExcellentCasesService.getAllByConId(conExcellentCases.getId());
        if(existByConId != null){
            throw new BusException("该合同已经存在优秀案例",BaseResultCode.GENERAL_ERROR);
        }
        conExcellentCases.setId(null);
        conExcellentCases.setContractName(conResourceMain.getContractName());
        conExcellentCases.setContractNumber(conResourceMain.getContractNumber());
        conExcellentCases.setConId(conResourceMain.getId());
        conExcellentCases.setTypeOfContract(1);
        conExcellentCases.setApplicant(currentUserName);
        //启动审批流程
        ProcessInstanceParam param = new ProcessInstanceParam();
        param.setBussinessId(conResourceMain.getId());
        param.setBpmKey(BpmInstanceService.CON_RESOURCE_BOM_KEY);
        Map<String,Object> map = new HashMap<>();
        try {
            map = ObjectUtils.objectToMap(conExcellentCases);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        map.put("moduleName","资源主合同");
        map.put("reason",conExcellentCases.getExcellent());
        map.put("serviceType",1);
        param.setParams(map);
        String processInstanceId = bpmInstanceService.startProcessInstance(param);
        conExcellentCases.setProcessInstanceId(processInstanceId);
        //conExcellentCases.setCreateBy(SecurityUtils.getUsername());
        conExcellentCasesService.save(conExcellentCases);
        conResourceMain.setExcellent(1);
        super.updateById(conResourceMain);
    }

    @Override
    public Map<String,Object> detail(Long id) {
        Map<String,Object> result = new HashMap<>(8);
        ConResourceMain conResourceMain = super.getById(id);
        result.put("data",conResourceMain);
        result.put("optRecord",conOperateService.listByConId(id));
        result.put("contractLabels",conAllLabelService.listByConId(id));
        List<ConFiles> conFiles = conFilesService.listByConId(id);
        if(conFiles!=null && conFiles.size()>0){
            conFiles.stream().forEach(c->{
                c.setUrl(c.getUrl().replace(httpUrl, httpsUrl));
                c.setNewUrl(c.getUrl());
            });
        }
        result.put("files",conFiles);
//        result.put("files",conFilesService.listByConId(id));
        // 创建一个查询包装器，用于构建查询条件
        QueryWrapper<ConResourceMemorandum> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("contract_number",conResourceMain.getContractNumber());
        // 使用查询包装器查询符合条件的合同备忘录列表
        List<ConResourceMemorandum> memorandumList = conResourceMemorandumMapper.selectList(queryWrapper);
        // 将查询结果放入结果集合中，键为 "memorandum"
        result.put("memorandum",memorandumList);
        return result;
    }

    @Override
    public void saveCon(ConResourceMain conResourceMain) {
        // 设置合同状态默认值为 已签订
        conResourceMain.setStatus(2);
        conResourceMain.setDelApply(0);

        conResourceMain.setContractName(editContractName(conResourceMain));
        conResourceMain.setContractNumber(editContractNumbers(conResourceMain));

        super.save(conResourceMain);
        ConFiles conFile = new ConFiles();
        conFile.setConId(conResourceMain.getId());
        conFile.setFileType(1);
        String path = conResourceMain.getFilePath();
        conFile.setUrl(path);
        conFile.setNewUrl(path);
        conFile.setFileName(path.substring(path.lastIndexOf("/")+1,path.length()));
        conFile.setScanPdf(FileUtil.getIsScanPdf(path));
        //保存附件
        conFilesService.save(conFile);
        conOperateService.saveByCon("新增合同",conResourceMain.getId());

        //触发消息通知
        SysMessageSend messageSend = new SysMessageSend();
        messageSend.setMessageUrl(ModuleUrlEnum.ZYHTZHTXQ.getUrl()+conResourceMain.getId());
        messageSend.setMessageType(MessageTypeEnum.MESSAGE_TYPE_1.getCode());
        messageSend.setContentParam(new String[]{"资源合同主合同"});
        remoteMessageSendService.messageSend(messageSend);
    }

    @Override
    public void updateCon(ConResourceMain conResourceMain) {
        ConResourceMain OldConResourceMain = conResourceMainMapper.getById(conResourceMain.getId());
        //原合同编号尾号+1，方便比较
        String oldContractNumber = incrementLastDigit(OldConResourceMain.getContractNumber());
        conResourceMain.setContractName(editContractName(conResourceMain));

        String newContractNumbers = editContractNumbers(conResourceMain);
        if (newContractNumbers.equals(oldContractNumber)){
            conResourceMain.setContractNumber(OldConResourceMain.getContractNumber());
        }else {
            conResourceMain.setContractNumber(newContractNumbers);
        }
        super.updateById(conResourceMain);

        ConExcellentCases conExcellentCases = conExcellentCasesService.getAllByConId(conResourceMain.getId());
        if(conExcellentCases != null){
            conExcellentCases.setContractName(conResourceMain.getContractName());
            conExcellentCases.setContractNumber(conResourceMain.getContractNumber());
            conExcellentCasesService.updateById(conExcellentCases);
        }

        conOperateService.saveByCon("修改合同",conResourceMain.getId());

        //触发消息通知
        SysMessageSend messageSend = new SysMessageSend();
        messageSend.setMessageUrl(ModuleUrlEnum.ZYHTZHTXQ.getUrl()+conResourceMain.getId());
        messageSend.setMessageType(MessageTypeEnum.MESSAGE_TYPE_2.getCode());
        messageSend.setContentParam(new String[]{conResourceMain.getContractName(),conResourceMain.getContractNumber()});
        remoteMessageSendService.messageSend(messageSend);
    }

    public static String checkChineseAndEnglish(String str) {
        boolean isEnglishWord = str.matches("[a-zA-Z0-9]+"); // 检查是否是英文单词（包括数字）

        if (isEnglishWord) {
            boolean containsSeparator = str.trim().matches(".*[\\s\\p{Punct}]+.*"); // 检查字符串中是否包含空格或其他分隔符

            if (!containsSeparator) {
                // 如果字符串中没有分隔符，则直接返回原字符串
                return str;
            }
        }

        boolean newWord = true; // 用于标记是否是一个新单词的开头
        StringBuilder result = new StringBuilder();
        for (char c : str.toCharArray()) {
            if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {
                String pinyin = PingYinUtil.getPinYinHeadChar(Character.toString(c));
                result.append(pinyin.toUpperCase());
            }
            else if (Character.isLetter(c)) {
                if (newWord) {
                    char firstLetter = Character.toUpperCase(c);
                    result.append(firstLetter);
                    newWord = false;
                }
            } else if (Character.isDigit(c)) {
                result.append(c);
            } else {
                newWord = true; // 遇到非字母字符，标记为新单词的开头
            }
        }
        return result.toString();
    }

    //根据信息拼接合同名字
    @Override
    public String editContractName(ConResourceMain conResourceMain){
        // 获取合同名字拼接字段
        String str1 = constantMapper.findConstLabel("贸易主体", String.valueOf(conResourceMain.getTradeBody()));
        String str2 = checkChineseAndEnglish(conResourceMain.getPartnerA());
        String str3 = checkChineseAndEnglish(conResourceMain.getPartnerB());
        Date signingDate = conResourceMain.getSigningDate();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
        String str4 = sdf.format(signingDate);
        // 合同名字拼接
        String ContractName = "MA-"+ str1 + "-" + str2 + "-" + str3 + "-" + str4;
        return ContractName;
    }

    //根据信息拼接合同编号
    @Override
    public String editContractNumbers(ConResourceMain conResourceMain){
        String str2 = checkChineseAndEnglish(conResourceMain.getPartnerA());
        String str3 = checkChineseAndEnglish(conResourceMain.getPartnerB());
        List<String> strings = conResourceMainMapper.getAllContractNumbers();
        // 创建合同编号对象
        String ContractNum;
        String str5 = "MA-" + str2 + "-" + str3;
        int maxNumber = extractAndFindMaxNumber(strings, str5);
        ContractNum = str5+"-"+maxNumber;
        return ContractNum;
    }

    @Override
    public String getNameById(Long mainContract) {
        String name = conResourceMainMapper.getNameById(mainContract);
        return name;
    }
}
